package com.zxy.express.util.wechat;

import com.autopai.base.common.tools.utils.JsonUtil;
import com.zxy.express.util.wechat.AccessTokenModel;
import com.zxy.express.util.wechat.HttpKit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class MiniProgramUtils {

    /**
     * 根据code获取openid
     *
     * @param appid
     * @param secret
     * @param jscode
     * @return
     * @throws Exception
     */
    public static String code2Session(String appid, String secret, String jscode, String url) throws Exception {
        Map<String, String> map = new HashMap<>(8);
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("js_code", jscode);
        map.put("grant_type", "authorization_code");
        return HttpKit.get(url, map);
    }

    /**
     * 生成小程序access_token
     *
     * @return
     * @throws Exception
     */
    public static AccessTokenModel getMiniAccessToken(String appid, String secret, String url) throws Exception {
        Map<String, String> map = new HashMap<>(8);
        map.put("grant_type", "client_credential");
        map.put("appid", appid);
        map.put("secret", secret);
        String json = HttpKit.get(url, map);
        if (StringUtils.isBlank(json) || json.indexOf("errcode") >= 0) {
            return null;
        }
        return JsonUtil.string2Obj(json, AccessTokenModel.class);
    }

}
